/* 
 * @Title: FileHelper.java
 * Created by liubingsr on 2012-6-13 下午2:17:24 
 * Copyright (c) 2012 Zhima Information Technology Co., Ltd. All rights reserved.
 */
package com.shaoshaohuo.app.utils;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

/**
 * @ClassName: FileHelper
 * @Description: 文件辅助类
 */
public class FileHelper {
	private final static String TAG = "FileHelper";
	private static int BUFFERSIZE = 1024;

	/**
	 * @Title: deleteFile
	 * @Description: 删除单个文件
	 * @param file
	 * @return void
	 */
	public static void deleteFile(String file) {
		if (!sdCardExist()) {
			return;
		}
		File f = new File(file);
		if (f != null && f.exists()) {
			f.delete();
		}
	}

	/**
	 * @Title: createFolder
	 * @Description: 新建文件夹
	 * @param folderPath
	 * @return boolean
	 */
	public static boolean createFolder(String folderPath) {
		if (!sdCardExist()) {
			return false;
		}
		if (!TextUtils.isEmpty(folderPath)) {
			File dir = new File(folderPath);
			if (dir != null && !dir.exists()) {
				return dir.mkdirs();
			}
		}
		return false;
	}

	/**
	 * @Title: deleteFolder
	 * @Description: 删除文件夹(递归删除此文件下所有文件)
	 * @param rootFolderPath
	 * @return void
	 */
	public static void deleteFolder(String rootFolderPath) {
		if (!sdCardExist()) {
			return;
		}
		File f = new File(rootFolderPath);
		if (f == null || !f.exists()) {
			return;
		}
		if (!f.delete()) {
			File[] fs = f.listFiles();
			for (int index = 0; index < fs.length; index++) {
				if (fs[index].isDirectory()) {
					deleteFolder(fs[index].getAbsolutePath());
				} else {
					fs[index].delete();
				}
			}
			f.delete();
		}
	}

	public static boolean fileExists(String fileFullName) {
		if (!sdCardExist()) {
			return false;
		}
		File f = new File(fileFullName);
		return f != null && f.exists();
	}


	public static String getTencentFileRoot(Context context) {
		String cacheDir = context.getFilesDir().getPath() + File.separator + "oauth.txt";
		return cacheDir;
	}



	private static String getFilePathForGroup(String root) {
		if (!root.endsWith("/"))
			root += "/";
		File f = new File(root);
		if (!f.exists()) {
			f.mkdirs();
		}
		return root;
	}


	/**
	 * @Title: getFileName
	 * @Description: 从全路径中得到文件名
	 * @param fullPath
	 * @return String
	 */
	public static String getFileName(String fullPath) {
		if (TextUtils.isEmpty(fullPath)) {
			return fullPath;
		}
		String fileName = "";
		int lastSeperator = fullPath.lastIndexOf('/');
		if (lastSeperator >= 0 && fullPath.length() > lastSeperator + 1) {
			fileName = fullPath.substring(lastSeperator + 1);
		} else {
			fileName = fullPath;
		}
		return fileName;
	}

	/**
	 * @Title: getFileExtension
	 * @Description: 取文件扩展名
	 * @param fullPath
	 * @return String
	 */
	public static String getFileExtension(String fullPath) {
		if (TextUtils.isEmpty(fullPath)) {
			return fullPath;
		}
		int pos = fullPath.lastIndexOf('.');
		if ((pos > 0) && (pos < (fullPath.length() - 1))) {
			return fullPath.substring(pos + 1);
		}
		return fullPath;
	}

	/**
	 * @Title: sdCardExist
	 * @Description: 检测手机是否存在sd card
	 * @return boolean
	 */
	public static boolean sdCardExist() {
		boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
		return sdCardExist;
	}

	/**
	 * @Title: getMIME
	 * @Description: 根据文件扩展名返回对应的MIME
	 * @param path
	 *            文件名
	 * @return String
	 */
	public static String getMIME(String path) {
		if (TextUtils.isEmpty(path)) {
			return "application/octet-stream";
		}
		int pos = path.lastIndexOf(".");
		if (pos > 0 && pos <= (path.length() - 1)) {
			String extension = path.substring(pos + 1).toLowerCase();
			if (extension.equals("gz")) {
				return "application/x-gzip";
			} else if (extension.equals("txt")) {
				return "text/plain";
			} else if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("jpe")) {
				return "image/jpeg";
			} else if (extension.equals("gif")) {
				return "image/gif";
			} else if (extension.equals("png")) {
				return "image/png";
			} else if (extension.equals("mp3")) {
				return "audio/mpeg";
			} else if (extension.equals("mpg") || extension.equals("mpeg") || extension.equals("mpe")) {
				return "video/mpeg";
			} else if (extension.equals("pdf")) {
				return "application/pdf";
			} else if (extension.equals("z")) {
				return "application/x-compress";
			} else if (extension.equals("zip")) {
				return "application/x-zip-compressed";
			} else if (extension.equals("wav")) {
				return "audio/x-wav";
			} else if (extension.equals("aac")) {
				return "audio/aac";
			} else if (extension.equals("m4a")) {
				return "audio/m4a";
			} else if (extension.equals("m4v")) {
				return "video/mp4";
			}
		}
		return "application/octet-stream";
	}

	/**
	 * @Title: isImageFile
	 * @Description: 是否是图片文件
	 * @param filePath
	 * @return boolean
	 */
	public static boolean isImageFile(String filePath) {
		if (TextUtils.isEmpty(filePath)) {
			return false;
		}
		int pos = filePath.lastIndexOf(".");
		if (pos > 0 && pos <= (filePath.length() - 1)) {
			String extension = filePath.substring(pos + 1).toLowerCase();
			if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("jpe")) {
				return true;
			} else if (extension.equals("png")) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * @Title: readStreamToByte
	 * @Description: 读文件
	 * @param is
	 * @return byte[]
	 */
	public static byte[] readStreamToByte(InputStream is) {
		byte[] result = null;
		try {
			result = new byte[is.available()];
			is.read(result);
		} catch (IOException e) {
			//Logger.getInstance(TAG).debug(e.getMessage(), e);
			return null;
		}
		return result;
	}

	/**
	 * @Title: getFileBytes
	 * @Description: 读文件
	 * @param fileUri
	 * @return byte[]
	 */
	public static byte[] getFileBytes(Uri fileUri) {
		if (fileUri == null) {
			return null;
		}
		return getFileBytes(fileUri.getPath());
	}

	/**
	 * @Title: getFileBytes
	 * @Description: 读取文件字节流
	 * @param fullPath
	 * @return byte[]
	 */
	public static byte[] getFileBytes(String fullPath) {
		if (TextUtils.isEmpty(fullPath)) {
			return null;
		}
		byte[] result = null;
		try {
			InputStream is = new FileInputStream(new File(fullPath));
			result = readStreamToByte(is);
			is.close();
		} catch (FileNotFoundException e) {
			//Logger.getInstance(TAG).debug(e.getMessage(), e);
		} catch (IOException e) {
			//Logger.getInstance(TAG).debug(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * @Title: writeFile
	 * @Description: 写文件
	 * @param fullPath
	 * @param bytes
	 * @return boolean
	 */
	public static boolean writeFile(String fullPath, byte[] bytes) {
		boolean result = false;
		try {
			FileOutputStream os = new FileOutputStream(fullPath);
			os.write(bytes, 0, bytes.length);
			os.close();
			result = true;
		} catch (Exception e) {
			result = false;
			//Logger.getInstance(TAG).debug(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * @Title: writeFile
	 * @Description: 写文件
	 * @param fullPath
	 * @param in
	 * @return boolean
	 */
	public static boolean writeFile(String fullPath, InputStream in) {
		boolean result = false;
		int len = 0;
		byte[] buffer = new byte[BUFFERSIZE];
		try {
			FileOutputStream os = new FileOutputStream(fullPath);
			while ((len = in.read(buffer)) > 0) {
				os.write(buffer, 0, len);
			}
			os.close();
			result = true;
		} catch (Exception e) {
			result = false;
			//Logger.getInstance(TAG).debug(e.getMessage(), e);
		}
		return result;
	}


	/**
	 * @Title: copyFile
	 * @Description: 文件复制
	 * @param srcFilePath
	 * @param destFilePath
	 * @return true 成功，false 失败
	 */
	public static boolean copyFile(String srcFilePath, String destFilePath) {
		try {
			File srcFile = new File(srcFilePath);
			File destFile = new File(destFilePath);
			InputStream in = new FileInputStream(srcFile);
			OutputStream out = new FileOutputStream(destFile);

			byte[] buf = new byte[BUFFERSIZE];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			return true;
		} catch (FileNotFoundException e) {
			//Logger.getInstance(TAG).debug(e.getMessage(), e);
		} catch (IOException e) {
			//Logger.getInstance(TAG).debug(e.getMessage(), e);
		}
		return false;
	}

	/**
	 * @Title: copyFile
	 * @Description: 文件复制
	 * @param destFilePath
	 * @return true 成功，false 失败
	 */
	public static boolean copyFile(InputStream in, String destFilePath) {
		try {
			File destFile = new File(destFilePath);
			if (destFile.exists()) {
				destFile.delete();
			}
			OutputStream out = new FileOutputStream(destFile);

			byte[] buf = new byte[BUFFERSIZE];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			return true;
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
		return false;
	}

	/**
	 * @Title: copyFile
	 * @Description: 文件复制
	 * @param srcFilePath
	 * @param destFilePath
	 * @return true 成功，false 失败
	 */
	public static boolean copyFileChannel(String srcFilePath, String destFilePath) {

		FileInputStream fi = null;

		FileOutputStream fo = null;

		FileChannel in = null;

		FileChannel out = null;

		File s = new File(srcFilePath);
		File t = new File(destFilePath);
		if (t.exists()) {
			t.delete();
		}

		try {

			fi = new FileInputStream(s);

			fo = new FileOutputStream(t);

			in = fi.getChannel();//得到对应的文件通道

			out = fo.getChannel();//得到对应的文件通道

			in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道
			return true;

		} catch (IOException e) {

			e.printStackTrace();
			return false;

		} finally {

			try {

				fi.close();

				in.close();

				fo.close();

				out.close();

			} catch (IOException e) {

				e.printStackTrace();

			}

		}
	}


	public static String convertStreamToString(InputStream is, String encoding) throws IOException {
		String line = null;
		if (is != null) {
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(is, encoding));
				line = reader.readLine();
			} finally {
				is.close();
			}
		}
		return (line == null) ? "" : line;
	}
}
